﻿using liaowa2.Common;
using liaowa2.Entity.DataModel;
using liaowa2.Entity.DTO;

using liaowa2.Interface.Manager;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace liaowa2.Web.Controllers
{
    public class ToolsController : BaseController
    {
        public INavigationInterface navigationAppService;
        public IManagerRoleInterface managerRoleAppService;
        public IManagerUserInterface managerUserAppService;

        public ToolsController(INavigationInterface navigationAppService, IManagerRoleInterface managerRoleAppService, IManagerUserInterface managerUserAppService)
        {
            this.navigationAppService = navigationAppService;
            this.managerRoleAppService = managerRoleAppService;
            this.managerUserAppService = managerUserAppService;
        }

        public ActionResult Admin()
        { //取得处事类型
            string action = Request.QueryString["action"];
            switch (action)
            {
                case "get_navigation_list": //获取后台导航字符串
                    System.Web.HttpContext c = System.Web.HttpContext.Current;
                    return Content(get_navigation_list(c));
            }
            return null;
        }

        #region 获取后台导航字符串==============================
        private string get_navigation_list(HttpContext context)
        {
            ManagerUser adminModel = GetAdmin();//获得当前登录管理员信息
            if (adminModel == null)
            {
                return "";
            }
            ManagerRoleDTO roleModel = managerRoleAppService.GetRoleDTO(adminModel.role_id); //获得管理角色信息
            if (roleModel == null)
            {
                return "";
            }
            string strWhere = " nav_type='" + DTEnums.NavigationEnum.System.ToString() + "' order by sort_id asc,id asc";
            List<Navigation> dt = navigationAppService.GetList(strWhere);
            this.get_navigation_childs(context, dt, 0, roleModel.role_type, roleModel.manager_role_values);
            return sb.ToString();
        }
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        private void get_navigation_childs(HttpContext context, List<Navigation> oldData, int parent_id, int role_type, List<ManagerRoleValue> ls)
        {
            //DataRow[] dr = oldData.Select("parent_id=" + parent_id);
            List<Navigation> newData = oldData.FindAll(c => c.parent_id == parent_id);
            bool isWrite = false;
            for (int i = 0; i < newData.Count; i++)
            {
                //检查是否显示在界面上====================
                bool isActionPass = true;
                if (newData[i].is_lock == 1)
                {
                    isActionPass = false;
                }
                //检查管理员权限==========================
                if (isActionPass && role_type > 1)
                {
                    string[] actionTypeArr = newData[i].action_type.Split(',');
                    foreach (string action_type_str in actionTypeArr)
                    {
                        //如果存在显示权限资源，则检查是否拥有该权限
                        if (action_type_str == "Show")
                        {
                            ManagerRoleValue modelt = ls.Find(p => p.nav_name == newData[i].name && p.action_type == "Show");
                            if (modelt == null)
                            {
                                isActionPass = false;
                            }
                        }
                    }
                }
                //如果没有该权限则不显示
                if (!isActionPass)
                {
                    if (isWrite && i == (newData.Count - 1) && parent_id > 0)
                    {
                        sb.Append("</ul>\n");
                    }
                    continue;
                }
                //如果是顶级导航
                if (parent_id == 0)
                {
                    sb.Append("<div class=\"list-group\">\n");
                    sb.Append("<h1 title=\"" + newData[i].sub_title + "\">");
                    if (!string.IsNullOrEmpty(newData[i].icon_url))
                    {
                        sb.Append("<img src=\"" + newData[i].icon_url + "\" />");
                    }
                    sb.Append("</h1>\n");
                    sb.Append("<div class=\"list-wrap\">\n");
                    sb.Append("<h2>" + newData[i].title + "<i></i></h2>\n");
                    //调用自身迭代
                    this.get_navigation_childs(context, oldData, newData[i].id, role_type, ls);
                    sb.Append("</div>\n");
                    sb.Append("</div>\n");
                }
                else //下级导航
                {
                    if (!isWrite)
                    {
                        isWrite = true;
                        sb.Append("<ul>\n");
                    }
                    sb.Append("<li>\n");
                    sb.Append("<a navid=\"" + newData[i].name + "\"");
                    if (!string.IsNullOrEmpty(newData[i].link_url))
                    {
                        if (newData[i].channel_id > 0)
                        {
                            sb.Append(" href=\"" + newData[i].link_url + "?channel_id=" + newData[i].channel_id + "\"");
                        }
                        else
                        {
                            sb.Append(" href=\"" + newData[i].link_url + "\"");
                        }
                    }
                    //if (!string.IsNullOrEmpty(newData[i]["icon_url"].ToString()))
                    //{
                    //    sb.Append(" icon=\"" + newData[i]["icon_url"].ToString() + "\"");
                    //}
                    sb.Append(">\n");
                    sb.Append("<span>" + newData[i].title + "</span>\n");
                    sb.Append("</a>\n");
                    //调用自身迭代
                    this.get_navigation_childs(context, oldData, newData[i].id, role_type, ls);
                    sb.Append("</li>\n");

                    if (i == (newData.Count - 1))
                    {
                        sb.Append("</ul>\n");
                    }
                }
            }
        }
        #endregion

        /// <summary>
        /// 导航菜单调用别名是否重复
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        public JsonResult CheckNavName(FormCollection collection)
        {
            string navName = Request.Form["param"];
            string old_name = Request.Form["name"];
            if (!string.IsNullOrEmpty(navName))
            {
                if (old_name.ToLower() == navName.ToLower())
                {
                    return Json(new { status = "y", info = "该导航别名可使用" });
                }
                List<Navigation> list = navigationAppService.GetList("name='" + navName + "'");
                if (list.Count > 0)
                {
                    return Json(new { status = "n", info = "该导航别名已被占用，请更换！" });
                }
                else
                {
                    return Json(new { status = "y", info = "该导航别名可使用" });
                }
            }
            return Json(new { status = "n", info = "该导航别名不可为空" });
        }

        public JsonResult CheckManagerUser(FormCollection collection)
        {
            string username = Request.Form["param"];
            string old_name = Request.Form["name"];

            if (!string.IsNullOrEmpty(username))
            {
                if (old_name.ToLower() == username.ToLower())
                {
                    return Json(new { status = "y", info = "用户名可使用" });
                }
                var result = managerUserAppService.CheckUserName(username);
                if (!result)
                {
                    return Json(new { status = "n", info = "用户名已被占用，请更换！" });
                }
                else
                {
                    return Json(new { status = "y", info = "用户名可使用" });
                }
            }
            return Json(new { status = "n", info = "请输入用户名" });
        }
    }
}